package org.example;

import com.mysql.cj.jdbc.Driver;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description: DriverManager测试
 * User: 王圆豪
 * Date: 2025-04-13
 * Time: 0:15
 */
public class Demo01_DriverManager {
    public static void main(String[] args) {
        ResultSet resultSet = null;
        Statement statement = null;
        Connection connection = null;
        try {
            //1. 加载数据库厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2. 获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1" +
                    ":3306/java113?characterEncoding=utf8&allowPublicKeyRetr" +
                    "ieval=true&useSSL=false", "root", "123456");
            //3. 创建Statement
            statement = connection.createStatement();
            //4. 定义SQL语句
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入姓名：");
            String name = sc.next();
            String sql = "select id, name, email, class_id from student where name = '" + name+ "'";
            //5. 执行sql语句
            resultSet = statement.executeQuery(sql);
            //6. 遍历并打印结果集
            while(resultSet.next()){
                long stuId = resultSet.getLong(1);
                String stuName = resultSet.getString(2);
                String stuMail = resultSet.getString(3);
                long stuClassId = resultSet.getLong(4);
                System.out.println(MessageFormat.format("学生编号={0}, 学生姓名={1}, 学生邮箱={2}, 学生班级={3}",
                        stuId,stuName,stuMail,stuClassId));
            }
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //7. 依次释放资源
            if(resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
